package Team

import (
	codecs "sanguo/codec/cs"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	ss_rpc "sanguo/protocol/ss/rpc"
	"sanguo/rpc/leaveTeam"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionLeaveTeam struct {
	transaction.TransactionBase
	user    *user.User
	req     *codecs.Message
	resp    *cs_message.LeaveTeamToC
	errcode cs_message.EnumType
}

func (this *transactionLeaveTeam) GetModuleName() string {
	return "Team"
}

func (this *transactionLeaveTeam) GetReplyMsg() proto.Message {
	return &cs_message.LeaveTeamToC{}
}

func (this *transactionLeaveTeam) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionLeaveTeam) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionLeaveTeam) Begin() {
	this.resp = &cs_message.LeaveTeamToC{}

	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()
	if nil == role || !role.IsRoleModleData() {
		node_game.Debugln(role.GetUserID(), "fail no selected role")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
	}

	_team := role.Team
	if _team == nil {
		node_game.Debugln(role.GetUserID(), role.GetID(), "LeaveTeam fail : role.Team == nil ")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	arg := &ss_rpc.LeaveTeamReq{
		TeamID: proto.Uint64(_team.TeamID),
		UserID: proto.String(role.GetUserID()),
		RoleID: proto.Uint64(role.GetID()),
	}

	leaveTeam.AsynCall(node_game.GetTeamServer().ToPeerID(), arg, transaction.TransTimeoutMs, func(resp *ss_rpc.LeaveTeamResp, err error) {
		if !this.user.CheckTrans(this) {
			//trans已经结束
			this.errcode = cs_message.EnumType_RETRY
			this.user.EndTrans(this)
			return
		}
		if nil == err && resp.GetOk() == 1 {
			role.Team = nil

			node_game.Debugln(role.GetUserID(), role.GetID(), "LeaveTeam Ok")
			this.errcode = cs_message.EnumType_OK
			this.user.EndTrans(this)
		} else {
			node_game.Debugln(role.GetUserID(), role.GetID(), "LeaveTeam fail")
			this.errcode = cs_message.EnumType_ERROR
			this.user.EndTrans(this)
		}
	})
}

func (this *transactionLeaveTeam) End() {
	this.resp.Errcode = cs_message.EnumType(this.errcode).Enum()
	this.user.Reply(this.req.GetSeriNo(), this.resp)
}

func (this *transactionLeaveTeam) Timeout() {
	this.errcode = cs_message.EnumType_RETRY
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.LeaveTeamToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionLeaveTeam{
			user: user,
			req:  msg,
		}
	})
}
